import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/hhldb/home'
  },
  // HHLDB 路由组
  {
    path: '/hhldb',
    name: 'hhldb',
    component: () => import('@/views/HHLDBLayout.vue'),
    children: [
      {
        path: 'home',
        name: 'hhldb-home',
        component: () => import('@/views/hhldb/HomeView.vue'),
        meta: { title: '首页 - HHLDB' }
      },
      {
        path: 'search',
        name: 'hhldb-search',
        component: () => import('@/views/hhldb/SearchView.vue'),
        meta: { title: '搜索 - HHLDB' }
      },
      {
        path: 'view',
        name: 'hhldb-view',
        component: () => import('@/views/hhldb/ViewController.vue'),
        meta: { title: '浏览 - HHLDB' }
      },
      {
        path: 'annotation',
        name: 'hhldb-annotation',
        component: () => import('@/views/hhldb/AnnotationView.vue'),
        meta: { title: '注释 - HHLDB' }
      },
      {
        path: 'analysis',
        name: 'hhldb-analysis',
        component: () => import('@/views/hhldb/AnalysisView.vue'),
        meta: { title: '分析 - HHLDB' }
      },
      {
        path: 'dataSource',
        name: 'hhldb-dataSource',
        component: () => import('@/views/hhldb/DataSourceView.vue'),
        meta: { title: '数据源 - HHLDB' }
      },
      {
        path: 'about',
        name: 'hhldb-about',
        component: () => import('@/views/hhldb/AboutView.vue'),
        meta: { title: '关于 - HHLDB' }
      },
      {
        path: 'tools',
        name: 'hhldb-tools',
        component: () => import('@/views/hhldb/ToolsView.vue'),
        meta: { title: '工具 - HHLDB' }
      }
    ]
  },
  // 用户相关路由
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/user/LoginView.vue'),
    meta: { title: '登录 - HHLDB' }
  },
  {
    path: '/welcome',
    name: 'welcome',
    component: () => import('@/views/user/WelcomeView.vue'),
    meta: { title: '欢迎 - HHLDB', requiresAuth: true }
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面未找到 - HHLDB' }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由标题处理
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  } else {
    document.title = 'HHLDB - 听力健康实验室数据库'
  }
  
  // 简单的路由守卫实现（后续可以扩展）
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next({ name: 'login' })
      return
    }
  }
  
  next()
})

export default router
